﻿using AntdUI;
using Lima.ResumeSys.Models;
using Lima.ResumeSys.Util;
using Lima.ResumeSys.Views;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Net.NetworkInformation;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace Lima.ResumeSys
{
    public partial class MainForm : AntdUI.Window
    {
        private UserControl currControl;
        private bool isUpdatingTabs = false;//用于阻止Tabs更新
        private System.Threading.Timer _timer;
        public MainForm()
        {
            InitializeComponent();
            //InitMenuData();
            UserControl control = new WellcomeControl(this) { Dock = DockStyle.Fill };
            AutoDpi(control);
            panel_content.Controls.Add(control);
            maintabs.Pages[0].Text = AntdUI.Localization.Get("home", "首页");
            //exitPanel.Back = Color.Transparent;
            lblCurrentUser.Text = $"欢迎你，{CurrentUser.UserName}";
            if (CurrentUser.IsAdmin == 0) {

                // 遍历 Items 查找匹配 Text 的菜单项
                foreach (AntdUI.MenuItem item in menu1.Items)
                {
                    if (item.Text == "组织架构")
                    {
                        menu1.Items.Remove(item);
                    }

                    if (item.Text == "用户管理")
                    {
                        menu1.Items.Remove(item);
                    }
                }
            }
            _timer = new System.Threading.Timer(CheckInternetConnection, null, 1200000, 1200000);
        }
        #region

        private void CheckInternetConnection(object state)
        {
            // 需要在UI线程上执行，所以使用Invoke
            this.Invoke((MethodInvoker)delegate
            {
                bool isConnected = IsInternetAvailableAsync();

                if (isConnected)
                {
                    // 确认退出
                    DialogResult result = MessageBox.Show("检测到外网连接请求！系统禁止联网，请立即退出", "退出确认",
                                                       MessageBoxButtons.YesNo,
                                                       MessageBoxIcon.Question);

                    if (result == DialogResult.Yes)
                    {
                        // 清理用户信息
                        CurrentUser.UserName = "";
                        CurrentUser.UserId = "";
                        CurrentUser.IsLoggedIn = false;
                        CurrentUser.UserOrgId = "";

                        // 关闭所有窗体
                        Application.Exit();
                      
                    }
                }
                else
                {
                    MessageBox.Show("网络未连接", "网络状态", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                }
            });
        }
        public  bool IsInternetAvailableAsync()
        {
            try
            {
                using (var client = new HttpClient())
                {
                    client.Timeout = TimeSpan.FromSeconds(3); // 3秒超时
                                                              // 访问百度（国内推荐）或 Google（如果可访问）
                    var response =  client.GetAsync("http://www.baidu.com");
                    return true;
                }
            }
            catch
            {
                return false;
            }
        }

        protected override void OnFormClosing(FormClosingEventArgs e)
        {
            _timer?.Dispose();
            base.OnFormClosing(e);
        }
        #endregion

        /// <summary>
        /// 菜单选择
        /// </summary>
        private void menu1_SelectChanged(object sender, MenuSelectEventArgs e)
        {
            string name = (string)e.Value.Text;
            // 检查是否已存在同名 TabPage
            foreach (var tab in maintabs.Pages)
            {
                if (tab is AntdUI.TabPage existingTab && existingTab.Text == name)
                {
                    isUpdatingTabs = true;
                    maintabs.SelectedTab = existingTab; // 直接跳转到已存在的 TabPage
                    isUpdatingTabs = false;
                    currControl = existingTab.Controls.Count > 0 ? existingTab.Controls[0] as UserControl : null;
                    return;
                }
            }
            // 如果不存在相应的 TabPage，创建新的
            UserControl control = null;
            switch (name)
            {
                case "首页":
                    control = new WellcomeControl(this);
                    break;
                case "人员信息":
                    control = new PersonInfoControl(this);
                    break;
                case "组织架构":
                    control = new OrganizationControl(this);
                    break;
                case "系统设置":
                    control = new SystemSettingControl(this);
                    break;
            }
            if (control != null)
            {
                //容器添加控件，需要调整dpi
                control.Dock = DockStyle.Fill;
                AutoDpi(control);
                AntdUI.TabPage tabPage = new AntdUI.TabPage()
                {
                    Text = name,
                };
                tabPage.BackColor = Color.White;
                tabPage.Controls.Add(control);
                maintabs.Pages.Add(tabPage);
                isUpdatingTabs = true;
                maintabs.SelectedTab = tabPage;
                isUpdatingTabs = false;
                currControl = control;
            }
        }

        private void btnExit_Click(object sender, EventArgs e)
        {
            SafeExitApplication();
        }

        private void MainForm_FormClosing(object sender, FormClosingEventArgs e)
        {
            // 如果用户点击X关闭窗体，执行安全退出
            if (e.CloseReason == CloseReason.UserClosing)
            {
                SafeExitApplication();
                e.Cancel = true; // 取消默认关闭行为
            }
        }
        private void SafeExitApplication()
        {
            // 确认退出
            DialogResult result = MessageBox.Show("确定要退出系统吗？", "退出确认",
                                               MessageBoxButtons.YesNo,
                                               MessageBoxIcon.Question);

            if (result == DialogResult.Yes)
            {
                // 清理用户信息
                CurrentUser.UserName = "";
                CurrentUser.UserId = "";
                CurrentUser.IsLoggedIn = false;
                CurrentUser.UserOrgId = "";

                // 关闭所有窗体
                Application.Exit();
            }
        }
        
    }
}
